<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
define('NOSESSION',true);
define('TC_API',true);
require_once '../core/core.php';
if($_AR['close']){
	exi('站点已关闭','error');
}
set_exi(function($message,$type,$action,$url){
	ob_clean();
	if($type=='error'){
		
		exit('');
	}else{
		$message=ijson_encode($message);
		exit($message);
	}
	
});
if(!$_RQ['msg_signature'] || !$_RQ['timestamp'] || !$_RQ['nonce']){
	exit('非法访问，只接受企业微信发起！');
}
//校验签名
//签名验证，交给不同的接口
/*if($_RQ['echostr']){
	$signkey = array($setting['token'], $_RQ['timestamp'], $_RQ['nonce'], $_RQ['echostr']);
}else{
	$signkey = array($setting['token'], $_RQ['timestamp'], $_RQ['nonce']);
}
sort($signkey, SORT_STRING);
$signString = implode('',$signkey);
$signString = sha1($signString);
if($signString !=$_RQ['msg_signature']){
	exit('error4');
}*/
if($_RQ['i']){
	$_SESSION['uniacid']=intval($_RQ['i']);
}
//来自自建应用
if($_RQ['app_id']){
	$wxwork_app=pdo_get('core_account_wxwork_app',array('id'=>intval($_RQ['app_id'])),array('id','pid','title','appid','appsecret','wxwork_id'));
	$wxwork=pdo_get('core_account_wxwork',array('id'=>$wxwork_app['wxwork_id']),array('id','appid','token','aeskey'));
	$setting['token']=$wxwork['token'];
	$setting['aeskey']=$wxwork['aeskey'];
	$corpid=$wxwork['appid'];
}else{
	$setting=core_setting('work_weixin');
	$setting['token']=$setting['token']?:'oNyvVWjt2pGrihehJ6p4uxeJwsre';
	if(!$setting['token']){
		exit('校验签名失败，未设置token！');
	}
	$corpid=$setting['corpid'];
}
if($_RQ['pid']){
	$corpid=pdo_getcolumn('core_open_plugin',array('id'=>intval($_RQ['pid'])),'suite_id');
	$corpid=$corpid?:$setting['corpid'];
	$_SESSION['workeropen_pid']=intval($_RQ['pid']);
}
//先将消息体解密
require ROOT_D.'/core/library/wxwork/callback/WXBizMsgCrypt.php';
$wxcpt=new WXBizMsgCrypt($setting['token'], $setting['aeskey'], $corpid);
$post=file_get_contents('php://input');
$message='';
//验证URL有效性
$DD=ijson_encode($_RQ);
if($_RQ['echostr']){
	$errCode = $wxcpt->VerifyURL($_RQ['msg_signature'],$_RQ['timestamp'], $_RQ['nonce'], $_RQ['echostr'], $message);
	if ($errCode == 0) {
		exit($message);
	}else{
		exit('消息体解密失败：'.$errCode);
	}
}else{
	$errCode = $wxcpt->DecryptMsg($_RQ['msg_signature'],$_RQ['timestamp'], $_RQ['nonce'], $post, $message);
}
if($errCode){
	exit('消息体解密失败：'.$errCode);
}
$postdata=xml2array($message);
if($postdata['InfoType']=='create_auth'){
	//安装创建通知/授权成功通知
	$suite_id=$postdata['SuiteId'];
	$AuthCode=$postdata['AuthCode'];
	if(!$_SESSION['workeropen_pid']){
		$plugin=pdo_get('core_open_plugin',array('suite_id'=>$suite_id));
		if(!$plugin){
			exit('找不到绑定的应用！');
		}
		$_SESSION['workeropen_pid']=$plugin['id'];
	}
	if(!$AuthCode){
		exit('缺少用户AuthCode，实例授权失败！');
	}
	//获取企业永久授权码/企业信息
	$content=model('core/wxwork_api',$_SESSION['workeropen_pid'])->get_permanent_code($AuthCode);
	//检查用户是否存在(通过企业微信ID作为唯一性)；
	$_SESSION['uniacid']=pdo_getcolumn('core_open_user',array('open_uid'=>$content['auth_corp_info']['corpid']),'uniacid');
	if($_SESSION['uniacid']){
		model('core/open_app')->update($_SESSION['workeropen_pid']);
	}else{
		//创建用户
		do{
			$username='wxwork_'.random(5,true);
			$username=$content['auth_user_info']['userid']?:$username;
			$check=pdo_getcolumn('core_users',array('name'=>$username),'id');
		}while($check);
		$work_weixin=core_setting('work_weixin');
		$new_member=array(
			'name'=>$username,
			'password'=>random(8),
			'groupid'=>$work_weixin['groupid'],
			'nickname'=>$content['auth_corp_info']['corp_name'],
		);
		if($postdata['mobile']){
			$new_member['mobile']=$postdata['mobile'];
		}
		$_SESSION['uniacid']=cfc('user')->create_user($new_member);
		$user=array(
			'uniacid'=>$_SESSION['uniacid'],
			'open_id'=>'1006',//1006表示来自企业微信的用户
			'open_uid'=>$content['auth_corp_info']['corpid'],
		);
		pdo_insert('core_open_user',$user);
	}
	exit('success');
}elseif($_GET['auth_code'] && $_GET['state']){
	//从服务商网站发起，获取当前会话
	session_id($_GET['state']);
	model('core/wxwork_api',$_SESSION['workeropen_pid'])->get_permanent_code($_GET['auth_code']);
}elseif($postdata['InfoType']=='suite_ticket'){
	//推送suite_ticket
	if($_RQ['pid']){
		pdo_update('core_open_plugin',array('suite_ticket'=>$postdata['SuiteTicket']),array('id'=>intval($_RQ['pid'])));
	}elseif($postdata['SuiteId']){
		pdo_update('core_open_plugin',array('suite_ticket'=>$postdata['SuiteTicket']),array('suite_id'=>$postdata['SuiteId']));
	}
}
exit('success');